from django.views import View
from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.shortcuts import redirect
from django.urls import reverse
from app01 import models
from app01.forms.server import ServerModelForm

class ServerListView(View):
    '''
    服务器列表的视图
    '''
    def get(self,request):
        queryset=models.Server.objects.all()
        return render(request,'server_list.html',{'queryset':queryset})

class ServerAddView(View):
    '''
    服务器添加的视图
    '''
    def get(self,request):

        form=ServerModelForm()
        return render(request,'server_change.html',{'form':form})
    def post(self,request):
        form=ServerModelForm(data=request.POST)
        if form.is_valid():
            form.save()
            return redirect(reverse('server_list'))
        else:
            return render(request,'server_change.html',{'form':form})
class ServerEditView(View):
    '''
    服务器编辑的视图
    '''
    def get(self,request,pk):
        obj=models.Server.objects.filter(pk=pk).first()
        if not obj:
            return HttpResponse('获取数据失败')
        form=ServerModelForm(instance=obj)
        return render(request,'server_change.html',{'form':form})
    def post(self,request,pk):
        obj = models.Server.objects.filter(pk=pk).first()
        if not obj:
            return HttpResponse('获取数据失败')
        form = ServerModelForm(instance=obj,data=request.POST)
        if form.is_valid():
            form.save()
            return redirect('server_list')
        else:
            return render(request,'server_change.html',{'form':form})
class ServerDeleteView(View):
    '''
    服务器删除的视图
    '''
    # def get(self,request,pk):
    #     return HttpResponse('delete ojbk')
    def post(self,request,pk):
        obj=models.Server.objects.filter(pk=pk).first()
        if not obj:
            return HttpResponse('获取数据失败')
        else:
            obj.delete()
            return HttpResponse('删除成功')